﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynaPrecision.LinearSystem
{
	public class MaximumAbsoluateErrorEvaluator<TData> : IIterativeErrorEvaluator<TData>
	{
		public MaximumAbsoluateErrorEvaluator()
		{
			this.ErrorLimit = DefaultValueProvider<TData>.GetDefaultResolution();
		}
		public TData ErrorLimit { get; set; }

		#region IIterativeErrorEvaluator<TInput> Members

		public TData EvaluateError<TMatrix>(TMatrix currentStep, TMatrix nextStep) where TMatrix : IMultiDimensionalArray<TData>
		{
			TData error = (dynamic)currentStep[0, 0] - nextStep[0, 0];
			for (int i = 0; i < currentStep.GetLength(0); i++)
			{
				for (int j = 0; j < currentStep.GetLength(1); j++)
				{
					TData currentError = _absoluteValue((dynamic)currentStep[i, j] - nextStep[i, j]);
					if (currentError > (dynamic)error)
					{
						error = currentError;
					}
				}
			}
			return error;
		}

		public bool IsErrorSatifactory(TData error)
		{
			return error < (dynamic)ErrorLimit;
		}

		#endregion

		private static TData _absoluteValue(TData value)
		{
			if (0 < (dynamic)value)
			{
				return value;
			}
			else
			{
				return -1 * (dynamic)value;
			}
		}
	}
}
